<?php

	include_once '../modelo/elements_model.php';
	include_once '../modelo/sections_model.php';
	include_once '../config.inc.php';
	include_once '../clases/menu_element.php'; 			
	include_once '../clases/image.php';
	
	class ControladorElementos {
		
		public $insertString = "";
		public $updateString = "";
		public $query = "";		
		public $ElmModel = null;
		public $SecModel = null;
		public $typeElement = "";
		public $tagImg = "Elemento de galer&iacute;a de im&aacute;genes";
		public $tagText = "Elemento de texto";
		public $tagMenu = "Elemento de men&uacute;";
		
		function __construct($typeElement = null){
			
			$this->ElmModel = new ElementsModel();			
			$this->SecModel = new SectionsModel();
						
			if ($typeElement != null){
				$this->typeElement = $typeElement;
				$this->setInsertQuery($this->typeElement);
				$this->setUpdateQuery($this->typeElement);
			}
		}
		
		private function setInsertQuery(){
			switch ($this->typeElement) {
				case TEXT_ELEMENT:  $this->insertString = "INSERT INTO ELEMENT_TEXT(SEC_ID,ELEMENT_ORDER,TEXT_CONTENT) VALUES ";
									break;	
				case MENU_LIST: $this->insertString = "INSERT INTO MENU_LIST(SEC_ID,ELEMENT_ORDER) VALUES";
				
								break;
								
				case MENU_ELEMENT: $this->insertString = "INSERT INTO MENU_ELEMENT(SEC_ID,MEN_ELEMENT_ID,ELEMENT_ORDER,ME_CONTENT,ME_LINK_TO) VALUES";
				
								break;
				
				case IMAGE_ELEMENT: $this->insertString = "INSERT INTO IMAGE_ELEMENT(IMAGE_ID,SEC_ID,ELEMENT_ORDER,IE_LINK_TO,GAL_ELEMENT_ID) VALUES";
						
							   break;
				case GALLERY_ELEMENT: $this->insertString = "INSERT INTO GALLERY_ELEMENT (SEC_ID,ELEMENT_ORDER) VALUES";
				
				break;								
			}
		}
		
		function createElement($arrayData){									
		    $query = $this->factoryInsertElements($arrayData);						
			return $this->ElmModel->createElement($query);
		}
		
		 private function factoryInsertElements($arrayData) {
			switch ($this->typeElement) {
				case TEXT_ELEMENT:  return $this->insertString."(".$arrayData["sec_id"].",".$arrayData["element_order"].",'".utf8_encode($arrayData["text_content"])."')";
									break;							
									
				case MENU_LIST: return $this->insertString."(".$arrayData["sec_id"].",".$arrayData["element_order"].")";
								break;
								
				case MENU_ELEMENT: return $this->insertString."(".$arrayData["sec_id"].",".$arrayData["men_element_id"].",".$arrayData["element_order"].",'".$arrayData["me_content"]."','".$arrayData["me_link_to"]."')";		
				
				case IMAGE_ELEMENT: return $this->insertString."(".$arrayData["image_id"].",".$arrayData["sec_id"].",".$arrayData["element_order"].",'".$arrayData["ie_link_to"]."',".$arrayData["gallery_id"].")";					
				
				case GALLERY_ELEMENT: return $this->insertString."(".$arrayData["sec_id"].",".$arrayData["element_order"].")";
			}
		}
		
		function obtainIdMenuList($appId,$secId){
						
			$this->query = "SELECT max(a.element_id) from menu_list a, sections b, applications c
where a.sec_id = b.sec_id and b.app_id = c.app_id and b.sec_id = ".$secId." and c.app_id = ".$appId."";	

			$select = $this->ElmModel->obtainIdMenuList($this->query);				
								
				while ($row = $select)
				  return $row[0];
		}
		
		function obtainIdGalleryImages($appId,$secId){
			
			$this->query = "SELECT max(a.element_id) from gallery_element a, sections b, applications c
where a.sec_id = b.sec_id and b.app_id = c.app_id and b.sec_id = ".$secId." and c.app_id = ".$appId."";	

			$select = $this->ElmModel->obtainIdMenuList($this->query);				
								
				while ($row = $select)
				  return $row[0];	
		}
		
		function obtainOrderNewElement($appId,$secId){
			
			$this->query = "SELECT A.t_elements + B.m_elements + C.m_elements elementos FROM
							(SELECT count(a.*) t_elements
							FROM element_text a, sections c, applications d
							WHERE a.sec_id = c.sec_id AND d.app_id = c.app_id AND d.app_id = ".$appId." AND c.sec_id = ".$secId.") A,
							(SELECT count(b.*) m_elements
							FROM menu_list b, sections c, applications d
							WHERE b.sec_id = c.sec_id AND d.app_id = c.app_id AND d.app_id = ".$appId." AND c.sec_id = ".$secId.") B, 
							(SELECT count(c.*) m_elements
							FROM gallery_element c, sections d, applications e
							WHERE c.sec_id = d.sec_id AND e.app_id = d.app_id AND e.app_id = ".$appId." AND d.sec_id = ".$secId.") C";
							
			$select = $this->ElmModel->obtainOrderNewElement($this->query);						
			
				while ($row = $select)
				  return $row[0];
		}
		
		function obtainSectionElements($appId,$secId){
			
			$this->query = "SELECT A.type_element, A.order_element, A.id FROM
							(((SELECT 'TE' type_element, a.element_order order_element, a.element_id id
						FROM element_text a, sections c, applications d
						WHERE a.sec_id = c.sec_id AND d.app_id = c.app_id AND d.app_id = ".$appId." AND c.sec_id = ".$secId." ORDER BY a.element_order)
						UNION
						(SELECT 'ML' type_element, b.element_order order_element, b.element_id id
						FROM menu_list b, sections c, applications d
						WHERE b.sec_id = c.sec_id AND d.app_id = c.app_id AND d.app_id = ".$appId." AND c.sec_id = ".$secId." ORDER BY b.element_order) UNION (SELECT 'GE' type_element, b.element_order order_element, b.element_id id
						FROM gallery_element b, sections c, applications d
						WHERE b.sec_id = c.sec_id AND d.app_id = c.app_id AND d.app_id = ".$appId." AND c.sec_id = ".$secId." ORDER BY b.element_order)) ORDER BY order_element) A
						";	
						
			$select = $this->ElmModel->obtainSectionElements($this->query);
			
			if (pg_num_rows($select) == 0){
				return '<p align="center"> <img src="../imagenes/noElementAnnouncment.png" width="503" height="273" /></p>'; 
			}
			else {
			$tagUpElements = '<table width="711" border="0"><tr><td width="382"> <ul id="sortable">';
			$tagDownElements = '</ul></td><td width="319"><h1 class="title"><img src="../imagenes/sections_move.png" width="346" height="192"></h1></td></tr></table>';
			$tagMiddleElements = '';
				$firstGalleryItem = 0;												
					while ($row = pg_fetch_row($select)) {
							set_time_limit(0);
							
						switch ($row[0]){
							
							case TEXT_ELEMENT: $tagMiddleElements = $tagMiddleElements. '<li class="inactivo"><span class="ui-icon ui-icon-arrowthick-2-n-s" id="'.$row[2].'"></span><input type="hidden" value="'.$row[1].'" id ="TE:'.$row[2].'"/><img src="../imagenes/editIcon.gif" onClick="redirectTextEditCall('.$row[2].')"/>&nbsp;<img src="../imagenes/deleteIcon.gif" onClick="deleteTextElement('.$row[2].')"/> &nbsp;'.$this->tagText.'</li>'; 							
							break;
							
							case MENU_LIST: $tagMiddleElements = $tagMiddleElements. '<li class="inactivo"><span class="ui-icon ui-icon-arrowthick-2-n-s" id="'.$row[2].'"></span><input type="hidden" value="'.$row[1].'" id ="ML:'.$row[2].'" /> <img src="../imagenes/editIcon.gif" onClick="redirectMenuListCall('.$row[2].')"/>&nbsp;<img src="../imagenes/deleteIcon.gif" onClick="deleteMenuListElement('.$row[2].')"/> &nbsp;'.$this->tagMenu.'</li>'; 							
							break;
							
							case GALLERY_ELEMENT:  $tagMiddleElements = $tagMiddleElements. '<li class="inactivo"><span class="ui-icon ui-icon-arrowthick-2-n-s" id="'.$row[2].'"></span><input type="hidden" value="'.$row[1].'" id ="GE:'.$row[2].'" /> <img src="../imagenes/editIcon.gif" onClick="redirectGalleryElementCall('.$row[2].')"/>&nbsp;<img src="../imagenes/deleteIcon.gif" onClick="deleteGalleryElement('.$row[2].')"/> &nbsp;'.$this->tagImg.'</li>'; 			 							break;
						}
					}
					
			return $tagUpElements.$tagMiddleElements.$tagDownElements;
			}
		}
		
		function obtaintTextContentForUpdate($appId,$secId,$elemId){			
			
			$this->query = "SELECT a.text_content
							FROM element_text a, sections c, applications d
							WHERE a.sec_id = c.sec_id AND d.app_id = c.app_id AND d.app_id = ".$appId." AND c.sec_id = ".$secId." AND a.element_id = ".$elemId."";
							
			$select = $this->ElmModel->searchContentElementText($this->query);
			
			while ($row = pg_fetch_row($select)) {
					set_time_limit(0);
					file_put_contents("../vistas/testIFrame.html","");
					file_put_contents("../vistas/testIFrame.html","<html><body>".$row[0]."</body></html />");
			}
		}
		
		private function obtainSelectSections($appId,$option){
			
			$this->query = "SELECT B.* FROM APPLICATIONS A, SECTIONS B WHERE A.APP_ID = B.APP_ID AND A.APP_ID = ".$appId;	
					
			$select = $this->SecModel->searchApplicationSections($this->query);
			
			  if ($option == 1)
				$middleTag = '';
			  else {
				$middleTag = array();
				$i = 0;  
			  }
			
			while ($row = pg_fetch_row($select)) {
					set_time_limit(0);
					
					if ($option == 1)
						$middleTag = $middleTag. '<option value="'.$row[2].'"> '.$row[2].'</option>';
					else {
						$middleTag[$i] = $row[2];
						$i = $i + 1;	
					}
			}
			
			return $middleTag;	
		}
		
		private function fillSelectActionOption($sections,$sectionName){
			for ($i = 0; $i < count($sections); $i++)
				if ($sections[$i] == $sectionName)
					return '<option value="'.$sections[$i].'"> '.$sections[$i].'</option>';
			
		}
		
		private function fillLeftSelect($sections,$sectionName){
		 
		  $options = "";
		  
			for ($i = 0; $i < count($sections); $i++)
				if ($sections[$i] != $sectionName)
					$options = $options.'<option value="'.$sections[$i].'"> '.$sections[$i].'</option>';
					
		  return $options;
		  
		}
		
		function obtainMenuSectionsForUpdate($appId,$secId,$elemId){
			
			$sections = $this->obtainSelectSections($appId,1);
			$sectionsArray = $this->obtainSelectSections($appId,2);
			
			$this->query = "SELECT m.* FROM menu_list a, sections c, applications d, menu_element m WHERE a.sec_id = c.sec_id AND d.app_id = c.app_id AND d.app_id = ".$appId." AND c.sec_id = ".$secId." AND m.men_element_id = ".$elemId."";
						
			$select = $this->ElmModel->searchMenuListOptions($this->query);
			
			$count = 0;
			$currents = pg_num_rows($select);
			
			$inputCurrentsElements = '<input type="hidden" id="currents" value="'.$currents.'" />';

			$tagsCurrents = '';

			while ($row = pg_fetch_row($select)) {
					set_time_limit(0);
			
			$upTagCurrents = '<input type="hidden" id="id[]" name="id[]" value="'.$row[0].'" />
						<table width="686" border="0" align="center" id="currentMenuElement'.$row[0].'">
						  <tr>						  
							<td width="141"><input type="text" name="currentOptionName[]" id="currentOptionName[]" class="inputOptionMenu" value="'.$row[4].'"></td>
							<td width="262">/ Indique Acci&oacute;n:
							   <select name="currentActionOptions[]" id="currentActionOptions[]" style="border-radius: 15px;
						width:150px;">'; 
						
			$bottomTagCurrents = '    </select></td>
    <td width="27"><img src="../imagenes/removeMenuOption.png" onClick="removeCurrentElement('.$row[0].')"/></td>
  </tr>
</table>
';	
						 if ($row[5] == ""){
						
						   	$optionsWithoutAction = '<option value="2"> No hacer nada </option><option value="0"> Seleccione -</option> <option value="1"> Ir a Sección </option> 
							</select></td>     <td width="201">/ Ir a: 
							  <select name="currentSectionsPath[]" id="currentSectionsPath[]" style="border-radius: 15px;
						width:150px;"> <option value="0"> Seleccione -</option>
						'.$sections;
						
						$tagsCurrents = $tagsCurrents.$upTagCurrents.$optionsWithoutAction.$bottomTagCurrents;		
								
						 }
						 else {
							$optionsWithAction = ' <option value="1"> Ir a Secci&oacute;n </option> <option value="0"> Seleccione -</option><option value="2"> No hacer nada </option>
							</select></td>     <td width="201">/ Ir a: 
							  <select name="currentSectionsPath[]" id="currentSectionsPath[]" style="border-radius: 15px;
						width:150px;">
						'.$this->fillSelectActionOption($sectionsArray,$row[5]).$this->fillLeftSelect($sectionsArray,$row[5]).' <option value="0"> Seleccione -</option>'; 
							 
							 $tagsCurrents = $tagsCurrents.$upTagCurrents.$optionsWithAction.$bottomTagCurrents;							 
						 }
						 
				
				$count = $count + 1;	
			}
			
			return $inputCurrentsElements.$tagsCurrents;
		}
		
		private function obtainImageForShow(Image $img,$folderImages){
			
			$this->query = 'SELECT a.* FROM images a, image_element b WHERE a.image_id = b.image_id and a.image_id ='. $img->getImageId();
			
			$select = $this->ElmModel->searchImagesOfGallery($this->query);
			
			while ($row = pg_fetch_row($select))
				return '<td width="63" rowspan="2" align="center" id="image'.$img->getImageGalleryId().'"><img src="'.$folderImages.$row[1].'" class="thumb"></td>
          <td width="33" height="59" id="imageDeleteButton'.$img->getImageGalleryId().'"><img src="../imagenes/removeMenuOption.png" onClick="removeImageElement('.$img->getImageGalleryId().');"/></td>';
		  
		}
		
		function obtainImagesSectionsForUpdate($appId,$secId,$elemId,$appName,$usrMail){
			
			$this->query = "SELECT m.* FROM gallery_element a, sections c, applications d, image_element m WHERE a.sec_id = c.sec_id AND d.app_id = c.app_id AND d.app_id = ".$appId." AND c.sec_id = ".$secId." AND m.gal_element_id = ".$elemId."";
			
			$select = $this->ElmModel->searchImagesOfGallery($this->query);
			$images = array();
			$i = 0;
			
			$upTagCurrentImages = '<table width="200" border="0"> <tr>';
			$middleUpTagImages = '</tr><tr>';
			$middleBottonTagImages = '';
			$bottomTagImages = '</tr></table>';
			
			while ($row = pg_fetch_row($select)) {
					set_time_limit(0);
					$images[$i] = new Image($row[1],$row[0],'');
					$i = $i + 1;
			}
			
			for ($j = 0; $j < count($images); $j++){
				$middleBottonTagImages = $middleBottonTagImages.'<td>&nbsp;</td>';			 	
				$upTagCurrentImages = $upTagCurrentImages.$this->obtainImageForShow($images[$j],ROUTE_APPLICATIONS_USERS.$usrMail."/Applications/".$appName."/images/");
			}
			
			return $upTagCurrentImages.$middleUpTagImages.$middleBottonTagImages.$bottomTagImages;
		}
		
		private function setUpdateQuery(){
			switch ($this->typeElement) {
				case TEXT_ELEMENT:  $this->updateString = "UPDATE ELEMENT_TEXT SET TEXT_CONTENT = ";
									break;	
				case MENU_ELEMENT:  $this->updateString = "UPDATE MENU_ELEMENT SET ";
							   break;				
				case IMAGE_ELEMENT: 
							   break;
				case GALLERY_ELEMENT: 
							   break;								
			}
		}
		
		function updateElement($arrayData){									
		    $query = $this->factoryUpdateElements($arrayData);						
			return $this->ElmModel->createElement($query);
		}
		
		 private function factoryUpdateElements($arrayData) {
			switch ($this->typeElement) {
				case TEXT_ELEMENT:  return $this->updateString."'".utf8_encode($arrayData["text_content"])."' WHERE ELEMENT_ID = ".$arrayData["element_id"];																							
				case MENU_ELEMENT: return $this->updateString. "ME_CONTENT = '".$arrayData["me_content"]."', ME_LINK_TO = '".$arrayData["me_link_to"]."' WHERE ELEMENT_ID = ".$arrayData["element_id"]; break;				
				case IMAGE_ELEMENT: break;
				case GALLERY_ELEMENT: break;
			}
		}
	}

?>